package net.chenyan.server.web;/**
 * @author chenyan
 * @createTime 2022/4/30 20:05
 * @description description
 */


import io.swagger.models.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Auther: sgy
 * @Date: 2019/12/9 22:08
 * @Description: TODO  模拟官网简单登陆，拦截器session效验token
 * @version: V1.0
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    /**
     * 进入controller层之前拦截请求
     *
     * @param httpServletRequest
     * @param
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o) throws Exception {
        String header = httpServletRequest.getHeader("Authorization");
        String method = httpServletRequest.getMethod();
        //处理预请求
        if (HttpMethod.OPTIONS.toString().equals(method)) {
            return true;
        }
        else {
            HttpSession session = httpServletRequest.getSession();
            String id = session.getId();
            System.out.println(id);
            String sessions = (String) session.getAttribute("sessions");
            if (sessions.equals(header)) {
                return true;
            }
        }
        log.info("---------------开始进入地址拦截器-------------------"+header);
        return false;
    }
    //访问controller之后 访问视图之前被调用
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }
    //访问视图之后被调用
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("---------------视图渲染之后的操作-------------------------0");
    }
}




